package com.example.auth.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.auth.entity.User;
import com.example.auth.response.Result;
import com.example.auth.service.AuthUserService;

import com.example.auth.service.UserService;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class AuthUserServiceImpl implements AuthUserService {


    @Autowired
    PasswordEncoder passwordEncoder;

    @Resource
    UserService userService;




    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getUsername, username));
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        return org.springframework.security.core.userdetails.User.withUsername(user.getUsername())
                .password(passwordEncoder.encode(user.getPassword()))
                .authorities("user","profile","message.read","message.write","other.scope")
                .roles("USER", "message.read", "message.write")
                .build();
    }


    /**
     * 获取用户信息
     *
     * @return
     */
    @Override
    public Result userInfo() {
        return null;
    }

    @Override
    public User getUserByEmail(String email) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<User>().eq(User::getEmail, email);
        return userService.getOne(wrapper);
    }

    @Override
    public User getUserByPhone(String phone) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<User>().eq(User::getPhone, phone);
        return userService.getOne(wrapper);
    }


}
